<template>
  <el-dialog
    title="新建连接"
    width="350"
    v-model="visible"
    :show-close="false"
    :modal="true"
    :close-on-click-modal="false"
  >
    <el-form label-width="auto" :model="device" @submit.native.prevent="addCommit">
      <el-form-item label="设备名称:" label-position="right">
        <el-input v-model="device.name"></el-input>
      </el-form-item>
      <el-form-item label="通讯类型:" label-position="right">
        <el-select v-model="device.protocol">
          <el-option
            v-for="protocolType in ProtocolTypeList"
            :key="protocolType"
            :label="protocolType"
            :value="protocolType"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="IP地址:" label-position="right">
        <el-input v-model="device.ip"></el-input>
      </el-form-item>
      <el-form-item label="端口号:" label-position="right">
        <el-input v-model.number="device.port"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-row class="custom-row">
        <el-form-item class="custom-form-item">
          <el-button type="primary" @click="addCommit">确定</el-button>
        </el-form-item>
        <el-form-item class="custom-form-item">
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-row>
    </template>
  </el-dialog>
</template>

<script setup name="AddConnection" lang="ts">
import {computed, ref} from "vue";
import {type Device} from "@/types/device";
import {useDeviceStore} from "@/stores/device";
import {ProtocolType, ProtocolTypeList} from "@/types/protocol_type.ts";

console.log(ProtocolTypeList)
let props = defineProps({
  dialogVisible: {
    type: Boolean,
    required: true,
  },
  setDialogVisible: {
    type: Function,
    required: true,
  },
});

const device = ref<Device>({
  id: 0,
  name: "",
  ip: "127.0.0.1",
  port: 502,
  protocol: ProtocolType.TCP,
  isConnected: false,
});
const visible = computed(() => props.dialogVisible);
const emit = defineEmits(["addSuccess"]);
const deviceStore = useDeviceStore();


const addCommit = async () => {
  props.setDialogVisible(false);
  const isSuccess = await deviceStore.addDevice(device.value);
  if (isSuccess) {
    emit(
      "addSuccess",
      device.value.name,
      device.value.ip,
      device.value.port,
      device.value.protocol,
    );
  }
};

const cancel = () => {
  props.setDialogVisible(false);
};
</script>

<style scoped>
.config-container {
  width: 400px;
  padding: 20px;
  text-align: left;
}

.el-form-item {
  margin-bottom: 15px;
}

.custom-row {
  display: flex;
  justify-content: center;
  /* 居中对齐 */
  align-items: center;
  /* 垂直居中（如果需要的话） */
}

.custom-form-item {
  margin: 0 10px;
  /* 左右的间距，根据需要调整 */
}

/* 如果你不想给第一个和最后一个元素添加边距，可以使用伪类选择器 */
.custom-row .custom-form-item:first-child {
  margin-left: 0;
}

.custom-row .custom-form-item:last-child {
  margin-right: 0;
}
</style>
